from django.contrib.auth.backends import ModelBackend
from users.models import User

class MyModelBackend(ModelBackend):
    """
    Authenticates against settings.AUTH_USER_MODEL.
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        """重写authenticate方法，实现用户通过用户名或密码都能登录"""

        try:
            user = User.objects.get(username=username)
        except:
            try:
                user = User.objects.get(mobile=username)
            except:
                return None

        if user.check_password(raw_password=password):
            return user
        else:
            return None
